package com.pktechan.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pktechan.api.base.BaseMapper;
import com.pktechan.api.base.BaseServiceImpl;
import com.pktechan.api.base.MiniProgramGlobalVar;
import com.pktechan.api.dao.WxMpMapper;
import com.pktechan.api.entity.WxMp;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.service.RedisService;
import com.pktechan.api.service.WxMpService;
import com.pktechan.api.utils.HttpUtil;
import com.pktechan.api.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: s.zhangbj03307
 * @create: 2021/3/9 11:17
 **/
@Service("wxMpService")
@Transactional
public class WxMpServiceImpl extends BaseServiceImpl<WxMp> implements WxMpService {

    private static final Logger logger = LoggerFactory.getLogger(WxMpServiceImpl.class);

    @Autowired
    private WxMpMapper wxMpMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public BaseMapper<WxMp> getBaseMapper() {
        return wxMpMapper;
    }

    /**
     * 根据MP_ID查询微信配置信息
     *
     * @param mpId
     * @return
     */
    @Override
    public WxMp getByMpId(String mpId) {
        return wxMpMapper.getByMpId(mpId);
    }

    /**
     * 获取公众号 accessToken
     *
     * @param wxMp
     * @return
     */
    @Override
    public String getMpAccessToken(WxMp wxMp) {
        //使用redis缓存accessToken
        String accessToken = redisService.getAccessTokenByMpId(wxMp.getMpId());
        logger.debug("redis缓存accessToken：" + accessToken);
        if (StringUtil.isEmpty(accessToken)) {
            //重新获取accessToken
            String getAccessTokenUrl = MiniProgramGlobalVar.GET_ACCESS_TOKEN.replace("APPID", wxMp.getAppId()).replace("APPSECRET", wxMp.getSecret());
            logger.debug("get access_token, url=" + getAccessTokenUrl);
            String resp = HttpUtil.reqJsonGet(getAccessTokenUrl);
            if (StringUtil.isEmpty(resp)) {
                logger.debug("微信服务器未返回数据。");
                throw new CustomException("微信服务器未返回数据。");
            }
            JSONObject tokenJO = JSONObject.parseObject(resp);
            accessToken = tokenJO.getString("access_token");
            logger.debug("重新获取accessToken：" + accessToken);
            //保存accessToken到redis中
            redisService.setAccessTokenByMpId(wxMp.getMpId(), accessToken);
        }
        logger.debug("redis缓存accessToken：" + accessToken);
        return accessToken;
    }
}
